﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using CONEK911Manager.BUS;
using CONEK911Manager.DTO;

namespace CONEK911Manager
{
    public partial class FormProductsManager : Form
    {
        List<ProductDTO> _listProduct = new List<ProductDTO>();
        readonly Dictionary<string, string> _textboxWithText = new Dictionary<string, string>();
        public FormProductsManager()
        {
            InitializeComponent();
            _textboxWithText.Add("txtSearchProduct", "Tìm kiếm (Mã sp, tên sp)");
            _textboxWithText.Add("txtProductCode", "Mã sản phẩm");
            _textboxWithText.Add("txtProductName", "Tên sản phẩm");
            _textboxWithText.Add("txtProductSize", "Kích thước");
            _textboxWithText.Add("txtProductPV", "Số PV");
            _textboxWithText.Add("txtProductQuantity", "Số lượng");
            _textboxWithText.Add("txtProductPriceNoVAT", "Giá chưa VAT");
            txtSearchProduct.Focus();
            LoadImage();
            BindData();
        }

        private void LoadImage()
        {
            btnAddUpdateProduct.Image = Base64String.ToImage(Base64String.Add);
            btnDeleteProduct.Image = Base64String.ToImage(Base64String.Delete);
            btnProductToExcel.Image = Base64String.ToImage(Base64String.Excel);
            btnSearchProduct.Image = Base64String.ToImage(Base64String.Search);
            btnViewAllProduct.Image = Base64String.ToImage(Base64String.List);
        }

        private void BindData()
        {
            lvProductInformation.Items.Clear();
            var productBus = new ProductBUS();
            _listProduct = productBus.GetAllProduct();
            foreach (var product in _listProduct)
            {
                string[] row = { product.Code, product.Name, product.Size, Convert.ToString(product.Pv), Convert.ToString(product.Quantity), Convert.ToString(product.Price) };
                var item = new ListViewItem(row);
                lvProductInformation.Items.Add(item);
            }
        }

        private void TxtProductCodeTextChanged(object sender, EventArgs e)
        {

        }

        private void ShowSuccess(string contents)
        {
            timer1.Enabled = false;
            timer1.Interval = 3000;
            timer1.Enabled = true;
            tssResult.ForeColor = Color.Green;
            tssResult.Text = contents;
        }

        private void ShowFail(string contents)
        {
            timer1.Enabled = false;
            timer1.Interval = 3000;
            timer1.Enabled = true;
            tssResult.ForeColor = Color.Red;
            tssResult.Text = contents;
        }

        private void Timer1Tick(object sender, EventArgs e)
        {
            tssResult.Text = "";
            timer1.Enabled = false;
        }

        private void BtnViewAllProductClick(object sender, EventArgs e)
        {
            BindData();
            txtSearchProduct.Text = "Tìm kiếm (Mã sp, tên sp)";
        }

        private void TxtSearchProductTextChanged(object sender, EventArgs e)
        {
            if (txtSearchProduct.Text != "Tìm kiếm (Mã sp, tên sp)")
            {
                var str = txtSearchProduct.Text.Trim();
                var searchResult = _listProduct.Where(product => product.Code.Contains(str) || product.Name.Contains(str)).ToList();
                BindResult(searchResult);
            }
        }

        private void BindResult(IEnumerable<ProductDTO> listProduct)
        {
            lvProductInformation.Items.Clear();
            foreach (var product in listProduct)
            {
                string[] row = { product.Code, product.Name, product.Size, Convert.ToString(product.Pv), Convert.ToString(product.Quantity), Convert.ToString(product.Price) };
                var item = new ListViewItem(row);
                lvProductInformation.Items.Add(item);
            }
        }

        private void TextBoxFocus(object sender, EventArgs e)
        {
            var textbox = sender as TextBox;

            if (textbox != null && textbox.Text.Equals(_textboxWithText[textbox.Name]))
            {
                textbox.Text = "";
            }
        }

        private void TextBoxLostFocus(object sender, EventArgs e)
        {
            var textbox = sender as TextBox;
            if (textbox != null && textbox.Text.Trim() == "")
            {
                textbox.Text = _textboxWithText[textbox.Name];
            }
        }

        private void BtnAddUpdateProductClick(object sender, EventArgs e)
        {
            try
            {
                var product = new ProductDTO
                                  {
                                      Name = txtProductName.Text.Trim(),
                                      Code = txtProductCode.Text.Trim(),
                                      Size = txtProductSize.Text.Trim(),
                                      Price = float.Parse(txtProductPriceNoVAT.Text.Trim()),
                                      Pv = float.Parse(txtProductPV.Text.Trim()),
                                      Quantity = float.Parse(txtProductQuantity.Text.Trim())
                                  };
                if (product.Name == "" || product.Code == "" || product.Size == "" 
                    || product.Name == "Tên sản phẩm" || product.Code == "Mã sản phẩm" || product.Size == "Kích thước")
                {
                    ShowFail("Vui lòng kiểm tra lại thông tin sản phẩm!");
                } else
                {
                    var productBus = new ProductBUS();
                    if (btnAddUpdateProduct.Text == "Thêm")
                    {
                        var check = productBus.AddProduct(product);
                        if (check)
                        {
                            ShowSuccess("Thêm sản phẩm thành công!");
                            BindData();
                            ResetFields();
                        }
                        else ShowFail("Mã sản phẩm đã tồn tại!");
                    } else
                    {
                        var check = productBus.UpdateProduct(product);
                        if (check)
                        {
                            ShowSuccess("Cập nhật sản phẩm thành công!");
                            BindData();
                            ResetFields();
                        } else ShowFail("Không cập nhật được sản phẩm!");
                    }
                    
                }
            }
            catch
            {
                ShowFail("Vui lòng kiểm tra lại thông tin sản phẩm!");
            }
            
        }
        
        private void ResetFields()
        {
            txtProductCode.Enabled = true;
            foreach (var pair in _textboxWithText)
            {
                Controls.Find(pair.Key, true)[0].Text = pair.Value;
            }
            btnAddUpdateProduct.Image = Base64String.ToImage(Base64String.Add);
            btnAddUpdateProduct.Text = "Thêm";
        }

        private void LvProductInformationSelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvProductInformation.SelectedItems.Count > 0)
            {
                txtProductCode.Enabled = false;
                btnAddUpdateProduct.Image = Base64String.ToImage(Base64String.Edit);
                btnAddUpdateProduct.Text = "Sửa";
                txtProductCode.Text = lvProductInformation.SelectedItems[0].SubItems[0].Text;
                txtProductName.Text = lvProductInformation.SelectedItems[0].SubItems[1].Text;
                txtProductSize.Text = lvProductInformation.SelectedItems[0].SubItems[2].Text;
                txtProductPV.Text = lvProductInformation.SelectedItems[0].SubItems[3].Text;
                txtProductQuantity.Text = lvProductInformation.SelectedItems[0].SubItems[4].Text;
                txtProductPriceNoVAT.Text = lvProductInformation.SelectedItems[0].SubItems[5].Text;
            } else
            {
                ResetFields();
            }
        }

        private void BtnDeleteProductClick(object sender, EventArgs e)
        {
            var productBus = new ProductBUS();
            if (productBus.RemoveProduct(txtProductCode.Text.Trim()))
            {
                ShowSuccess("Xóa sản phẩm thành công!");
                BindData();
                ResetFields();
            } else
            {
                ShowFail("Không xóa được sản phẩm này!");
            }
        }

        private void FormProductsManagerLoad(object sender, EventArgs e)
        {
            
        }

        private void LvProductInformationResize(object sender, EventArgs e)
        {
            lvProductInformation.Columns[0].Width = lvProductInformation.Width * 10 / 100;
            lvProductInformation.Columns[2].Width = lvProductInformation.Width * 10 / 100;
            lvProductInformation.Columns[3].Width = lvProductInformation.Width * 15 / 100;
            lvProductInformation.Columns[4].Width = lvProductInformation.Width * 15 / 100;
            lvProductInformation.Columns[5].Width = lvProductInformation.Width * 15 / 100;
            lvProductInformation.Columns[1].Width = lvProductInformation.Width * 35 / 100;
        }

        private void LvProductInformationColumnClick(object sender, ColumnClickEventArgs e)
        {
            
        }

        private void FormProductsManagerClick(object sender, EventArgs e)
        {
            
        }
    }
}
